import {Image, ScrollView, Swiper, SwiperItem, Text, View} from '@tarojs/components'
import Taro, {useDidShow} from '@tarojs/taro'
import type React from 'react'
import {useCallback, useState} from 'react'
import {type Exhibition, getExhibitions} from '@/api'

const Home: React.FC = () => {
  const [exhibitions, setExhibitions] = useState<Exhibition[]>([])
  const [loading, setLoading] = useState(true)

  const loadData = useCallback(async () => {
    setLoading(true)
    try {
      const result = await getExhibitions('ongoing')
      if (result.success && result.data) {
        setExhibitions(result.data)
      } else {
        Taro.showToast({
          title: result.error || '加载失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('加载数据失败:', error)
      Taro.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
    } finally {
      setLoading(false)
    }
  }, [])

  useDidShow(() => {
    loadData()
  })

  const handleExhibitionClick = (id: number) => {
    Taro.navigateTo({
      url: `/pages/exhibition/index?id=${id}`
    })
  }

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr)
    return `${date.getMonth() + 1}月${date.getDate()}日`
  }

  const parseHighlights = (highlights?: string | string[]): string[] => {
    // 如果已经是数组，直接返回
    if (Array.isArray(highlights)) return highlights
    // 如果是字符串，尝试解析
    if (!highlights) return []
    try {
      return JSON.parse(highlights)
    } catch {
      return []
    }
  }

  return (
    <View style={{background: 'linear-gradient(to bottom, #EFF6FF, #DBEAFE)', minHeight: '100vh'}}>
      <ScrollView scrollY className="box-border" style={{height: '100vh', background: 'transparent'}}>
        {exhibitions.length > 0 && (
          <View className="mb-4">
            <Swiper
              className="rounded-b-2xl overflow-hidden"
              indicatorColor="rgba(255, 255, 255, 0.5)"
              indicatorActiveColor="#ffffff"
              circular
              autoplay
              interval={5000}
              style={{height: '400px'}}>
              {exhibitions.slice(0, 3).map((exhibition) => {
                // 获取第一张图片
                const firstImage = Array.isArray(exhibition.image_url) ? exhibition.image_url[0] : exhibition.image_url
                return (
                  <SwiperItem key={exhibition.id}>
                    <View className="relative w-full h-full" onClick={() => handleExhibitionClick(exhibition.id)}>
                      <Image src={firstImage || ''} mode="aspectFill" className="w-full h-full" />
                      <View className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-6">
                        <Text className="text-white text-2xl font-bold block mb-2">{exhibition.title}</Text>
                        <Text className="text-white/90 text-sm block">
                          {exhibition.subtitle || exhibition.location}
                        </Text>
                      </View>
                    </View>
                  </SwiperItem>
                )
              })}
            </Swiper>
          </View>
        )}

        <View className="px-4 pb-4">
          <View className="flex items-center justify-between mb-4">
            <Text className="text-xl font-bold text-blue-900">热门展览</Text>
            <View className="i-mdi-fire text-2xl text-orange-500"></View>
          </View>

          {loading ? (
            <View className="text-center py-12">
              <Text className="text-gray-500">加载中...</Text>
            </View>
          ) : exhibitions.length === 0 ? (
            <View className="text-center py-12">
              <Text className="text-gray-500">暂无展览</Text>
            </View>
          ) : (
            <View className="space-y-4">
              {exhibitions.map((exhibition) => {
                const highlights = parseHighlights(exhibition.highlights)
                // 获取第一张图片，如果是数组则取第一个，否则使用原值
                const firstImage = Array.isArray(exhibition.image_url) ? exhibition.image_url[0] : exhibition.image_url
                return (
                  <View
                    key={exhibition.id}
                    className="bg-white rounded-2xl shadow-md overflow-hidden transition-all active:scale-98"
                    onClick={() => handleExhibitionClick(exhibition.id)}>
                    <Image src={firstImage || ''} mode="aspectFill" className="w-full h-48" />
                    <View className="p-4">
                      <Text className="text-lg font-bold text-gray-900 block mb-2">{exhibition.title}</Text>
                      <Text className="text-sm text-gray-600 block mb-3">
                        {exhibition.subtitle || exhibition.description}
                      </Text>

                      <View className="flex items-center mb-3">
                        <View className="i-mdi-map-marker text-blue-600 mr-2"></View>
                        <Text className="text-sm text-gray-700">{exhibition.location}</Text>
                      </View>

                      <View className="flex items-center mb-3">
                        <View className="i-mdi-calendar text-blue-600 mr-2"></View>
                        <Text className="text-sm text-gray-700">
                          {formatDate(exhibition.start_date)} - {formatDate(exhibition.end_date)}
                        </Text>
                      </View>

                      {highlights.length > 0 && (
                        <View className="flex flex-wrap gap-2 mb-3">
                          {highlights.slice(0, 3).map((highlight, index) => (
                            <View key={index} className="bg-blue-50 px-3 py-1 rounded-full">
                              <Text className="text-xs text-blue-700">{highlight}</Text>
                            </View>
                          ))}
                        </View>
                      )}

                      <View className="flex items-center justify-between pt-3 border-t border-gray-100">
                        <View className="flex items-center">
                          <View className="i-mdi-ticket text-amber-600 mr-1"></View>
                          <Text className="text-sm text-gray-600">多种票型可选</Text>
                        </View>
                        <View className="flex items-center text-blue-600">
                          <Text className="text-sm font-bold mr-1">立即购票</Text>
                          <View className="i-mdi-chevron-right text-lg"></View>
                        </View>
                      </View>
                    </View>
                  </View>
                )
              })}
            </View>
          )}
        </View>
      </ScrollView>
    </View>
  )
}

export default Home
